package mobileann.mafamily.utils;

import java.util.ArrayList;
import java.util.List;
import com.baidu.mapapi.map.offline.MKOLUpdateElement;
import com.baidu.mapapi.map.offline.MKOfflineMap;
import com.baidu.mapapi.map.offline.MKOfflineMapListener;

public class BMapOfflineUtil{
	private static MKOfflineMap mOffLine = null;
	private static int iRefCount = 0;
	private static List<MKOfflineMapListener> lstMapListener;

	private final static String AUTO_UPDATE = "AutoUpdate";

	public static synchronized MKOfflineMap getOfflineMap(MKOfflineMapListener aListener){
		if(mOffLine == null){
		    lstMapListener = new ArrayList<MKOfflineMapListener>();		    
		    mOffLine = new MKOfflineMap();
	        mOffLine.init(new MKOfflineMapListener() {

	            @Override
	            public void onGetOfflineMapState(int arg0, int arg1) {
	                // TODO Auto-generated method stub
	                for(MKOfflineMapListener l : lstMapListener) {
	                    l.onGetOfflineMapState(arg0, arg1);
	                }
	            }
	        }); 
		}
		iRefCount++;
		if (aListener != null) {
		    if (!lstMapListener.contains(aListener)) {
		        lstMapListener.add(aListener);		        
		    }
		}
		return mOffLine;
	}
	
	public static synchronized void destory() {
	    iRefCount--;
	    if (iRefCount <= 0) {
            mOffLine.destroy();
            mOffLine = null;    
            lstMapListener.clear();
	    }
	}

	/**
	 * wifi下自动更新
	 */
	public static synchronized void autoUpdate(){        
        if (NetUtils.getInstance().netstate() == 2
                && SPUtils.getWifiAutoUpdate(AUTO_UPDATE)) {
            ArrayList<MKOLUpdateElement> localMapList = mOffLine
                    .getAllUpdateInfo();
            if (localMapList != null && localMapList.size() != 0) {
                for (MKOLUpdateElement e : localMapList) {
                    if (e.update) {
                        mOffLine.remove(e.cityID);
                        mOffLine.start(e.cityID);
                    }
                }
            }
        }        
	}
	
	public static void offlineMapCheck(){
		int count = SPUtils.getOfflineMapCheck() + 1;
		if(count == 3){
			SPUtils.setOfflineMapCheck(0);
			getOfflineMap(null);
			autoUpdate();
		}else{
			SPUtils.setOfflineMapCheck(count);
		}
	}
}
